package com.sf.sms.software.action;

import com.sf.sms.user.entity.User;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 80002004 on 2016/8/29.
 */
@Controller
@RequestMapping("/softwareUpload")
public class SoftwareUploadAction {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/upload")
    public String upload() {
        return "upload";
    }

    @ResponseBody
    @RequestMapping("/uploadFile")
    public Map<String, Object> uploadSoftware(HttpSession session,
            @RequestParam("softwarefile") MultipartFile file) {
        Map<String, Object> resultMaps = new HashedMap();

        if(!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String filePath = session.getServletContext().getRealPath("/downloadTemp/");
            String prefix = UUID.randomUUID().toString();
            String fileName = prefix + originalFilename;
            File newFile = new File(filePath, fileName);

            try {
                InputStream is = file.getInputStream();
                FileUtils.copyInputStreamToFile(is, newFile);
                resultMaps.put("status", "success");
                resultMaps.put("filePath", "/downloadTemp/" + fileName);
                resultMaps.put("fileSize", file.getSize());
            } catch (IOException ex) {
                logger.error(ExceptionUtils.getRootCauseMessage(ex));
                resultMaps.put("errorMsg", ex);
                return resultMaps;
            }
        } else {
            resultMaps.put("errorMsg", "上传文件失败，请重新上传！");
            return resultMaps;
        }
        return resultMaps;
    }
}
